package org.belkodevelop.course.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.belkodevelop.course.domen.Course;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.xml.xpath.Jaxp13XPathTemplate;
import org.springframework.xml.xpath.XPathOperations;

import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.util.Calendar;
import java.util.Date;

@Service
public class CourseService {

    private final Log log = LogFactory.getLog(getClass());

    private final String COURSES_INFO = "https://api.privatbank.ua/p24api/pubinfo?exchange&coursid=5";
    private final int TIME_CACHE_HOUR = 1;

    private Course cacheCourse;
    private Date cacheDate;

    private RestTemplate rest = new RestTemplate();
    private XPathOperations xpath = new Jaxp13XPathTemplate();

    public Course getCourse(String ccy, String baseCyy) {

        Calendar cacheDateCalendar = null;
        if (cacheDate != null) {
            cacheDateCalendar = Calendar.getInstance();
            cacheDateCalendar.setTime(cacheDate);
            cacheDateCalendar.add(Calendar.HOUR_OF_DAY, TIME_CACHE_HOUR);
        }

        if (cacheDate == null || cacheDateCalendar.getTime().before(new Date())) {
            String result = rest.getForObject(COURSES_INFO, String.class);

            Course course = new Course();
            course.setCcy(ccy);
            course.setBaseCcy(baseCyy);
            course.setSale(xpath.evaluateAsDouble("//*[local-name() = 'exchangerate'][@ccy='USD'][@base_ccy='UAH']/@sale", new StreamSource(new StringReader(result))));
            course.setBuy(xpath.evaluateAsDouble("//*[local-name() = 'exchangerate'][@ccy='USD'][@base_ccy='UAH']/@buy", new StreamSource(new StringReader(result))));
            cacheCourse = course;
            cacheDate = new Date();

            log.debug(cacheCourse);

            return course;
        }
        return cacheCourse;
    }
}
